package com.lagou.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author czq
 * @date 2020/9/2 22:29
 */
@Activate(group = {CommonConstants.CONSUMER})
public class TransportIPFilter implements Filter {

    private static final String UNKNOWN = "unKnown";

    private static final String LOCAL_IP = "0:0:0:0:0:0:0:1";

    private static final String LOCAL_IP_ADDRESS = "127.0.0.1";

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = getIpAddress(request);
        if (ip.equals(LOCAL_IP)) {
            ip = LOCAL_IP_ADDRESS;
        }
        RpcContext.getContext().setAttachment("clientIp", ip);
        return invoker.invoke(invocation);
    }

    /**
     * 获取 IP 地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }

        ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isEmpty(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
            return ip;
        }

        return request.getRemoteAddr();
    }
}
